#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/25 15:58
# @Author  : 王凯
# @File    : auto_driver.py
# @Project : scrapy_spider
import time

from appium import webdriver
from appium.common.exceptions import NoSuchContextException
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
from selenium.common import NoSuchElementException


class AutoDriver:
    def __init__(self, device_name="RVBBB21B24205069", platform_version="10"):
        capabilities = {
            "platformName": "Android",
            "platformVersion": "10",
            "deviceName": "RVBBB21B24205069",
            "appPackage": "com.xunmeng.pinduoduo",
            "appActivity": ".ui.activity.MainFrameActivity",
            "noReset": "true",
            "fullReset": "false",
        }

        appium_server_url = "http://localhost:4723/wd/hub"

        self.driver = webdriver.Remote(appium_server_url, options=UiAutomator2Options().load_capabilities(capabilities))
        # 获取模拟器/手机的分辨率(px)
        size = self.driver.get_window_size()

        self.start_x = size["width"] * 0.5
        self.start_y = size["height"] * 0.7
        self.end_x = size["width"] * 0.5
        self.end_y = size["height"] * 0.3

    def _find_element(self, by, value, sleep=1, raise_error=True):
        for _ in range(30):
            try:
                ele = self.driver.find_element(by=by, value=value)
                return ele
            except NoSuchElementException as e:
                time.sleep(sleep)
                continue
            except Exception as e:
                if raise_error:
                    raise e

    def search(self, query_key):
        """需要是首页"""
        top_bar = self._find_element(by=AppiumBy.XPATH, value='//android.widget.TextView[@content-desc="搜索"]')
        top_bar.click()

        change_bar = self._find_element(by=AppiumBy.XPATH, value='//android.widget.TextView[@content-desc="商品"]')
        change_bar.click()

        change_shop_bar = self._find_element(
            by=AppiumBy.XPATH, value="//android.view.ViewGroup[2]/android.widget.LinearLayout[1]"
        )
        change_shop_bar.click()
        time.sleep(2)
        input_bar = self._find_element(by=AppiumBy.XPATH, value='//android.widget.EditText[@content-desc="搜索"]')
        input_bar.send_keys(query_key)
        time.sleep(2)

        search_bar = self._find_element(by=AppiumBy.XPATH, value='//android.widget.TextView[@text="搜索"]')

        search_bar.click()

    def come_in_shop(self, index=1):
        shop = self._find_element(by=AppiumBy.XPATH, value=f'(//android.widget.TextView[@content-desc="进店"])[{index}]')
        shop.click()

        all_goods = self._find_element(by=AppiumBy.XPATH, value='//android.widget.TextView[@text="全部商品"]')
        all_goods.click()

        all_goods_sort = self._find_element(by=AppiumBy.XPATH, value='//android.widget.TextView[@text="销量"]')
        all_goods_sort.click()

        # 一直滑动到 有 “本店暂无更多商品” 的字样显示
        while True:
            self.driver.swipe(self.start_x, self.start_x, self.end_x, self.end_y)
            try:
                time.sleep(2)
                no_more_goods = self.driver.find_element(
                    by=AppiumBy.XPATH, value='//android.widget.TextView[@text="本店暂无更多商品"]'
                )
                if no_more_goods:
                    break
            except NoSuchElementException as e:
                continue
            except Exception as e:
                print(e)
                raise e

    def back_to_home(self):
        while True:
            self.driver.back()
            try:
                time.sleep(2)
                top_bar = self.driver.find_element(
                    by=AppiumBy.XPATH, value='//android.widget.TextView[@content-desc="搜索"]'
                )
                if top_bar:
                    break
            except NoSuchElementException as e:
                continue
            except Exception as e:
                print(e)
                break

    def run(self):
        for query_key in ["上海调味品", "金祥服饰服装店"]:
            self.search(query_key)
            self.come_in_shop(1)
            self.back_to_home()


if __name__ == "__main__":
    test = AutoDriver()
    test.run()
